package test.mina;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.util.Scanner;

import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoConnector;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

public class SimpleChatClient {
	
	public static void main(String[] args) {
		IoConnector connector = new NioSocketConnector();
		connector.setConnectTimeoutMillis(30000);
		connector.getFilterChain().addLast("codec", 
                new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8"))));
		connector.setHandler(new IoHandlerAdapter() {
			@Override
			public void messageReceived(IoSession session, Object message) throws Exception {
				System.out.println(message);
			}
		});
		ConnectFuture future = connector.connect(new InetSocketAddress("localhost", 6868));
		future.awaitUninterruptibly();
		IoSession session = future.getSession();
		while(true) {
//			Scanner s = new Scanner(System.in);
//			String text = s.nextLine();
			BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
			String text;
			try {
				text = br.readLine();
				session.write(text);
			} catch (IOException e) {
				e.printStackTrace();
			}
//			s.close();
		}
	}

}
